<template>
  <el-dialog width="700px" v-bind="$attrs" @close="handleClose" @open="handleOpen">
    <div v-if="step === 1" class="m-center w-10/12" style='margin-top: 25px;'>
      <el-form @submit.prevent.native label-width="170px" :model="formOldEmail" ref="oldEmailForm" :rules="oldRules">
        <el-form-item :label="$t('system.user.profile.current_email') + ':'" prop="email">
          <el-input
            maxlength="64"
            show-word-limit
            v-model="formOldEmail.email"
            disabled
            :placeholder="$t('system.user.profile.current_email')"
          >
            <el-tooltip slot="append" class="item" effect="dark" :content="$t('system.user.profile.send_tip')" placement="top-start">
              <el-button :disabled="verifyCodeSendDisabled" :loading="emailSendLoading"  icon="el-icon-s-promotion" @click="sendEmailVerifyCode(formOldEmail)">{{ countDown }}</el-button>
            </el-tooltip>

          </el-input>
        </el-form-item>
        <el-form-item :label="$t('system.user.profile.verifyCode') + ':'" prop="verifyCode">
          <el-input
            maxlength="4"
            show-word-limit
            v-model="formOldEmail.verifyCode"
            @blur="() => formOldEmail.verifyCode = formOldEmail.verifyCode.trim()"
            :placeholder="$t('system.user.profile.verifyCode')"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="step === 2" class="m-center w-10/12" style='margin-top: 25px;'>
      <el-form @submit.prevent.native label-width="170px" :model="formNewEmail" ref="newEmailForm" :rules="newRules">
        <el-form-item :label="$t('system.user.profile.new_email') + ':'" prop="email">
          <el-input
            maxlength="64"
            show-word-limit
            v-model="formNewEmail.email"
            @blur="() => formNewEmail.email = formNewEmail.email.trim()"
            @input="emailChange"
            :placeholder="$t('system.user.profile.new_email')"
          >
            <el-tooltip slot="append" class="item" effect="dark" :content="$t('system.user.profile.send_tip')" placement="top-start">
              <el-button :disabled="verifyCodeSendDisabled" :loading="emailSendLoading"  icon="el-icon-s-promotion" @click="sendEmailVerifyCode(formNewEmail)">{{ countDown }}</el-button>
            </el-tooltip>

          </el-input>
        </el-form-item>
        <el-form-item :label="$t('system.user.profile.verifyCode') + ':'" prop="verifyCode">
          <el-input
            maxlength="4"
            show-word-limit
            v-model="formNewEmail.verifyCode"
            @blur="() => formNewEmail.verifyCode = formNewEmail.verifyCode.trim()"
            :placeholder="$t('system.user.profile.verifyCode')"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">{{ $t('page.cancel') }}</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="confirmLoading"
        @click="handleConfirm()"
      >{{ step == 1 ? $t('common.next') : $t('common.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { editUserEmail, sendVerifyCode, verifyAuthCode } from '@/api/user'
export default {
  inheritAttrs: false,
  data() {
    return {
      emailRegex: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
      step: 1,
      confirmLoading: false,
      verifyCodeSendDisabled: false,
      emailSendLoading: false,
      oldEmail: '',
      countDown: '',
      timer: null,
      formOldEmail: {
        email: '',
        verifyCode: '',
        editEmailFlag: true,
      },
      formNewEmail: {
        email: '',
        verifyCode: '',
        editEmailFlag: false,
      },
      oldRules: {
        email: [
          {
            required: true,
            message: 'Please input email',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: 'Email format error',
            trigger: 'blur'
          }
        ],
        verifyCode: [
          {
            required: true,
            message: 'Please input verify code',
            trigger: 'blur'
          }
        ]
      },
      newRules: {
        email: [
          {
            required: true,
            message: 'Please input email',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: 'Email format error',
            trigger: 'blur'
          }
        ],
        verifyCode: [
          {
            required: true,
            message: 'Please input verify code',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    init(email){
      console.log("email", email)
      this.formOldEmail.email = email
      if(!email || this.emailRegex.test(email) === false){
        this.step = 2
        this.$nextTick(() => {
          this.$refs['newEmailForm'].resetFields()
        })
      }
    },
    emailChange(value){
      if(value && this.formOldEmail.email != value){
        this.verifyCodeSendDisabled = false
      } else {
        this.verifyCodeSendDisabled = true
      }
    },
    handleClose() {
      // this.$refs['oldEmailForm'].resetFields()
      // this.$refs['newEmailForm'].resetFields()
      this.timer && this.clearTimer()
      this.step = 1
      this.confirmLoading = false
      this.$nextTick(() => {
        this.$refs['oldEmailForm'].resetFields()
      })
      this.$emit('update:visible', false)
      this.$emit('submit')
    },
    handleConfirm() {
      if(this.step == 1){
        this.verifyEmailCode()
      } else {
        this.editEmail()
      }
    },
    verifyEmailCode(){
      this.$refs['oldEmailForm'].validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          verifyAuthCode(false, this.formOldEmail).then((res) => {
            this.confirmLoading = false
            this.step = 2
            this.timer && this.clearTimer()
            this.$nextTick(() => {
              this.$refs['newEmailForm'].resetFields()
            })
          }).catch((e) => {
            this.confirmLoading = false
            this.$confirmError(e)
          })
        }
      })
    },
    editEmail() {
      this.$refs['newEmailForm'].validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          this.formNewEmail.oldEmail = this.formOldEmail.email
          this.formNewEmail.oldVerifyCode = this.formOldEmail.verifyCode
          editUserEmail(this.formNewEmail).then((res) => {
            this.handleClose()
            this.confirmLoading = false
            this.$message.success(this.$t('common.operated_successfully'))
          }).catch((e) => {
            this.confirmLoading = false
            this.$confirmError(e)
          })
        } else {
          return false
        }
      })
    },
    handleOpen() {

    },
    clearTimer(){
      clearInterval(this.timer)
      this.countDown = ''
      this.verifyCodeSendDisabled = false
    },
    sendEmailVerifyCode(data){
      let email = this.formOldEmail.email
      if(this.step == 2){
        email = this.formNewEmail.email
      }
      if(this.emailRegex.test(email)){
        this.doSend(data)
      } else {
        this.$message.error(this.$t('modules.login.message.invalid_email_format'))
      }
    },
    doSend(data){
      this.emailSendLoading = true

      sendVerifyCode(data).then((res) => {
        this.$message.success(this.$t('system.user.profile.send_success_tip'))
        this.emailSendLoading = false
        this.countDown = 60
        this.verifyCodeSendDisabled = true
        this.timer = setInterval(() => {
          this.countDown--
          if(this.countDown == 0){
            this.timer && this.clearTimer()
          }
        }, 1000)
      }).catch((e) => {
        this.$confirmError(e)
        this.emailSendLoading = false
      })
    }
  },
  mounted() {},
}
</script>

<style>
</style>
